package com.etonenet.test.hazelcast.nearcache;

import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.monitor.LocalMapStats;

public class Server {
	public static final String GROUP_NAME = "groupName";
	public static final String GROUP_PASSWORD = "groupPassword";

	private final static Logger logger = LoggerFactory.getLogger(Server.class);

	public static void main(String[] args) {
		new Server();
	}

	private IMap<Object, Object> nearCacheMap;

	public Server() {
		Config config = new Config();
		config.setProperty("hazelcast.logging.type", "slf4j");
		config.getGroupConfig().setName(GROUP_NAME).setPassword(GROUP_PASSWORD);

		//@formatter:off
		
		// mapconfig
//		MapConfig mapConfig = new MapConfig();
//		mapConfig.setName("default").setInMemoryFormat(InMemoryFormat.NATIVE);
//		mapConfig.setBackupCount(0).setAsyncBackupCount(1).setReadBackupData(true);
//		MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
//		mapStoreConfig.setWriteDelaySeconds(60).setWriteBatchSize(1000);
//		MapIndexConfig mapIndexConfig = mapConfig.getMapIndexConfigs().;
//		mapIndexConfig.setAttribute("id").setOrdered("true");
//		mapIndexConfig.setAttribute("name").setOrdered("false");
//		config.addMapConfig(mapConfig);

		//@formatter:on

		HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
		nearCacheMap = instance.getMap("nearCacheMap");
		nearCacheMap.put("test", "test");

		monitor.run();
	}

	Runnable monitor = new Runnable() {
		public void run() {
			while (true) {
				LocalMapStats localMapStats = nearCacheMap.getLocalMapStats();
				long hits = localMapStats.getHits();
				long maxGetLatency = localMapStats.getMaxGetLatency();
				long lastAccessTime = localMapStats.getLastAccessTime();
				Calendar instance = Calendar.getInstance();
				instance.setTimeInMillis(lastAccessTime);
				logger.info("hits :{} , maxGetLatency :{} ,lastAccessTime :{}", hits, maxGetLatency,
						instance.getTime());

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};
}
